using System;
using System.Collections.Generic;
using System.Text;
using SharpObjects.Configuration;
using SharpObjects.Configuration.ConfigurationProviders;
using SharpObjects.Interfaces;

namespace SharpObjects.Data
{
    /*
  <sql_statements>
    <statement id="insert_folder_tree">
      <sql>
        insert into folder_tree (id, parentid, childid, datemodified, modifiedby, datecreated, createdby )
        values ({0}, {1}, {2}, {3}, {4}, {5}, {6})
      </sql>
      <parameters>id, parentid, childid, datemodified, modifiedby, datecreated, createdby </parameters>
    </statement>
    <statement id="insert_items">
      <sql>
        insert into items (itemid, description )
        values ({0}, {1})
      </sql>
      <parameters>itemid, description </parameters>
    </statement>
  </sql_statements>
     
     */

    public class SqlStatement : IXmlInitializable 
    {
        public bool IsInitialized { get; set; }

        protected readonly static char[] delimiters = new char[] { ',', ';' };
        protected readonly static char[] white_space = new char[] { '\t', '\n', '\v', '\f', '\r' }; // 9, 10, 11, 12, 13

        public string Id { get; set; }
        public List<string> Parameters { get; set; }
        public string Sql { get; set; }

        public SqlStatement()
        {
            this.Parameters = new List<string>();
        }


        #region IXmlInitializable Members

        
        /*
        <statement id="insert_items">
            <sql>
            insert into items (itemid, description )
            values ({0}, {1})
            </sql>
            <parameters>itemid, description </parameters>
        </statement>
        */
        public void Initialize(System.Xml.XmlElement initializationXmlElement)
        {
            IConfigurationProvider config = new XmlConfigurationProvider(initializationXmlElement);

            this.Id = config.GetString("@id");

            string sql = config.GetString("sql");

            for (int k = 0; k < white_space.Length; k++)
            {
                sql = sql.Replace(white_space[k], ' ');
            }

            this.Sql = sql.Trim();
            string parameterString = config.GetString("parameters");
            string [] parameters = parameterString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

            for (int k = 0; k < parameters.Length; k++)
            {
                parameters[k] = parameters[k].Trim();
            }

            this.Parameters.AddRange(parameters);

            this.IsInitialized = true;
        }


        #endregion
    }
}
